package com.tcm.controller.backend;

import com.tcm.common.enums.ResponseEnum;
import com.tcm.entity.bo.ClozeItemExcel;
import com.tcm.entity.dto.ClozeItemUpdateDto;
import com.tcm.entity.dto.param.ClozeItemPageParam;
import com.tcm.entity.vo.BatchImportResult;
import com.tcm.entity.vo.ClozeItemListResult;
import com.tcm.entity.resp.PageR;
import com.tcm.entity.resp.R;
import com.tcm.exception.DatabaseOperationException;
import com.tcm.service.ClozeItemService;
import com.tcm.utils.AccessTokenUtil;
import com.tcm.utils.ItemUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 填空题题目管理控制器
 * @author Guqier
 * @version 1.0
 * @date 2023/7/12 21:53
 */
@Slf4j
@RestController
@RequestMapping("/pc/item/cloze")
public class ClozeItemController {

    @Autowired
    private ClozeItemService clozeItemService;

    /**
     * 解析填空题题目
     * @param param 参数
     * @return 解析结果
     */
    @RequestMapping(value = "/analyse", method = RequestMethod.POST)
    public R analyseClozeItemContent(@RequestBody Map<String, String> param){
        Map<String, Object> res = new HashMap<>();
        String content = param.get("content");
        String markContent = ItemUtil.analyzeClozeItemToMarkContent(content);
        List<String> answer = ItemUtil.analyzeClozeItemToAnswer(content);
        List<Map<String, String>> collect = answer.stream().map(ans -> {
            Map<String, String> one = new HashMap<>();
            one.put("rank", String.valueOf(ans.charAt(0)));
            one.put("ans", ans.substring(1));
            return one;
        }).collect(Collectors.toList());
        res.put("markContent", markContent);
        res.put("ans", collect);
        String originContent = markContent;
        for (String s : answer) {
            originContent = originContent.replaceFirst("_", "{" + s + "}");
        }
        res.put("content", originContent);
        return R.success(res);
    }

    /**
     * 添加填空题
     * @param clozeItemUpdateDto 填空题更新数据封装类
     * @param request http请求体
     * @return 添加响应结果
     */
    @RequestMapping(method = RequestMethod.POST)
    public R addClozeItem(@RequestBody @Valid ClozeItemUpdateDto clozeItemUpdateDto, HttpServletRequest request){
        boolean res = false;
        try {
            res = clozeItemService.addClozeItem(clozeItemUpdateDto, AccessTokenUtil.getUserId(request));
        } catch (Exception e) {
            return R.fail(0, e.getMessage());
        }
        return res ? R.success() : R.fail(ResponseEnum.PARAM_IS_INVAlID);
    }

    /**
     * 删除填空题
     * @param ids 题目ID列表
     * @param request http请求
     * @return 响应结果
     */
    @RequestMapping(method = RequestMethod.DELETE)
    public R removeClozeItem(@RequestParam("ids") List<Long> ids, HttpServletRequest request){
        if (ids.isEmpty()) {
            return R.fail(ResponseEnum.PARAM_IS_BLANK);
        }
        boolean res = false;
        try {
            res = clozeItemService.removeClozeItem(ids, AccessTokenUtil.getUserId(request));
        } catch (Exception e) {
            return R.fail(0, e.getMessage());
        }
        return res ? R.success() : R.fail(ResponseEnum.PARAM_IS_INVAlID);
    }

    /**
     * 分页获取填空题列表
     * @param param 分页参数
     * @return 填空题列表
     */
    @RequestMapping(method = RequestMethod.GET)
    public R getClozeItemListByPage(ClozeItemPageParam param){
        if (param.getPage() == null || param.getPageSize() == null){
            return R.fail(ResponseEnum.PARAM_IS_BLANK);
        }
        PageR<ClozeItemListResult> clozeItemListByPage = clozeItemService.getClozeItemListByPage(param);
        return R.success(clozeItemListByPage);
    }

    /**
     * 修改填空题信息
     * @param clozeItemUpdateDto 填空题数据Dto
     * @param request http请求对象
     * @return 响应结果
     */
    @RequestMapping(method = RequestMethod.PUT)
    public R modifyClozeItem(@RequestBody @Valid ClozeItemUpdateDto clozeItemUpdateDto, HttpServletRequest request){
        if (clozeItemUpdateDto.getItemId() == null) {
            return R.fail(ResponseEnum.PARAM_IS_BLANK);
        }
        boolean res = false;
        try {
            res = clozeItemService.modifyClozeItem(clozeItemUpdateDto, AccessTokenUtil.getUserId(request));
        } catch (DatabaseOperationException e) {
            return R.fail(0, e.getMessage());
        }
        return res ? R.success() : R.fail(ResponseEnum.PARAM_IS_INVAlID);
    }

    /**
     * 批量导入填空题
     * @param file excel文件
     * @param request http请求对象
     * @return 校验信息
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public R batchImportClozeItem(@RequestParam MultipartFile file, HttpServletRequest request){
        BatchImportResult<ClozeItemExcel> result = null;
        try {
            result = clozeItemService.importClozeItem(file, AccessTokenUtil.getUserId(request));
        } catch (Exception e) {
            return R.fail(0, e.getMessage());
        }
        return R.success(result);
    }

    /**
     * 确认导入填空题
     * @param uuid 导入uuid
     * @param request http请求对象
     * @return 响应结果
     */
    @RequestMapping(value = "/import", method = RequestMethod.PUT)
    public R confirmBatchClozeItem(String uuid, HttpServletRequest request){
        boolean res = false;
        try {
            res = clozeItemService.confirmBatchClozeItem(uuid, AccessTokenUtil.getUserId(request));
        } catch (DatabaseOperationException e) {
            return R.fail(0, e.getMessage());
        }
        return res ? R.success() : R.fail(ResponseEnum.CACHE_NOT_EXIST);
    }

    /**
     * 导出导入失败题目列表
     * @param uuid 导入uuid
     * @param response http响应对象
     * @return 响应结果
     */
    @RequestMapping(value = "/import", method = RequestMethod.GET)
    public R exportImportFailedClozeItem(String uuid, HttpServletResponse response){
        try {
            clozeItemService.exportImportFailedClozeItem(uuid, response);
        } catch (Exception e) {
            return R.fail(0, e.getMessage());
        }
        return R.success();
    }

    /**
     * 导出填空题信息
     * @param param 参数封装
     * @param response http响应对象
     * @return 导出文件
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public R exportClozeItem(ClozeItemPageParam param, HttpServletResponse response){
        try {
            clozeItemService.exportClozeItem(param, response);
        } catch (IOException e) {
            return R.fail(0, e.getMessage());
        }
        return null;
    }

    /**
     * 根据ID列表查询填空题
     * @param ids 填空题ID列表
     * @return 填空题列表展示对象集合
     */
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public R getClozeItemByIds(@RequestParam("ids") List<Long> ids){
        if (CollectionUtils.isEmpty(ids)) {
            return R.fail(ResponseEnum.PARAM_IS_BLANK);
        }
        return R.success(clozeItemService.getClozeItemByIds(ids));
    }

}
